package test;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.lsda.util.Util;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LsdaDBMoniter implements org.quartz.Job, Serializable{

	Logger log = LoggerFactory.getLogger(LsdaDBMoniter.class);
	
	private int count = 0;
	
	public int detectNewTaskInDB(){
		int ret = 0;
		try {
			Connection conn = Util.getConnection();
			String sql_task = "select count(*) as n from task where status = 0";
			PreparedStatement ps_task = conn.prepareStatement(sql_task);
			ResultSet rs_task = ps_task.executeQuery();
			if(rs_task.next()){
				ret = rs_task.getInt("n");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e){
			e.printStackTrace();
		}
		return ret;
	}
	
	public int getCount(){
		return this.count;
	}
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// TODO Auto-generated method stub
		this.count = detectNewTaskInDB();
		JobKey key = context.getJobDetail().getKey();
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        dataMap.put("count", this.count);
		log.info("There have been " + this.count + " new tasks added since last scan.");
	}
}
